package com.hxit.huaxiamelongarden.common;

import com.hxit.huaxiamelongarden.utils.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@WebFilter("/*")
public class JwtAuthFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(JwtAuthFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        response.setContentType("application/json; charset=UTF-8");
        String requestURI = request.getRequestURI();

        // 排除不需要验证的路径
        if (requestURI.equals("/login") || requestURI.equals("/register") ||
                requestURI.equals("/captcha") || requestURI.startsWith("/doc.html") ||
                requestURI.startsWith("/webjars") || requestURI.startsWith("/v3/api-docs") || requestURI.startsWith("/ws")) {
            filterChain.doFilter(request, response); // 放行
            return;
        }

        String token = request.getHeader("Authorization");
        if (token != null) {
            if (JwtUtil.validateToken(token)) {
                String userId = JwtUtil.getUserIdFromToken(token);
                request.setAttribute("userId", userId);
                logger.info("令牌验证成功，用户ID：{}", userId); // 打印中文日志
            } else {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("无效或过期的令牌。");
                logger.warn("无效或过期的令牌。"); // 打印中文日志
                return;
            }
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("缺少授权头或授权头无效。");
            logger.warn("缺少授权头或授权头无效。"); // 打印中文日志
            return;
        }

        filterChain.doFilter(request, response);
    }
}


